#include "StdAfx.h"
#include "AdditiveInstrument.h"
#include "Notes.h"


CAdditiveInstrument::CAdditiveInstrument(void)
{
}


CAdditiveInstrument::~CAdditiveInstrument(void)
{
}

void CAdditiveInstrument::Start()
{
    mSynth.SetSampleRate(GetSampleRate());
    mSynth.Start();
	mADSR.SetSource( &mSynth );
	mTime = 0.0;
}

void CAdditiveInstrument::SetNote( CNote *aNote )
{
	// Get a list of all attribute nodes and the
    // length of that list
    CComPtr<IXMLDOMNamedNodeMap> attributes;
    aNote->Node()->get_attributes(&attributes);
    long len;
    attributes->get_length(&len);

    // Loop over the list of attributes
    for(int i=0;  i<len;  i++)
    {
        // Get attribute i
        CComPtr<IXMLDOMNode> attrib;
        attributes->get_item(i, &attrib);

        // Get the name of the attribute
        CComBSTR name;
        attrib->get_nodeName(&name);

        CComVariant value;
        attrib->get_nodeValue(&value);

        if(name == "duration")
        {
            value.ChangeType(VT_R8);
            mADSR.SetDuration(value.dblVal);
        }
        else if(name == "note")
        {
            //SetFreq(NoteToFrequency(value.bstrVal));
        }
        else if(name == "attack")
        {
            value.ChangeType(VT_R8);
            //mADSR.SetAttack(value.dblVal);
        }
        else if(name == "release")
        {
            value.ChangeType(VT_R8);
            mADSR.SetRelease(value.dblVal);
        }
    }
}

bool CAdditiveInstrument::Generate()
{
	mSynth.Generate();
    bool valid = mADSR.Generate();

    mFrame[0] = mADSR.Frame(0);
    mFrame[1] = mADSR.Frame(1);

	mTime += GetSamplePeriod();
    return valid;
}